package com.example.algorithm.no0006.solution;

import com.example.algorithm.no0006.Solution;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 解答-Z字形变换
 * 通过从左向右迭代字符串，我们可以轻松地确定字符位于 Z 字形图案中的哪一行
 * 时间复杂度：O(n)，其中n==len(s)
 * 空间复杂度：O(n)
 * @ClassName MapSolution
 * @Author Administrator
 * @Date 2020/5/20 10:26
 * @Version 1.0.0
 */
public class SolutionImpl implements Solution {
    @Override
    public String convert(String s, int numRows) {
        if(numRows == 1) return s;

        List<StringBuilder> rows = new ArrayList<>();
        for(int i = 0; i < Math.min(numRows, s.length()); i++) {
            rows.add(new StringBuilder());
        }
        int curRow = 0, flag = -1;
        for(char c : s.toCharArray()) {
            rows.get(curRow).append(c);
            if(curRow == 0 || curRow == numRows -1) {
                flag = - flag;
            }
            curRow += flag;
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rows) {
            res.append(row);
        }
        return res.toString();
    }
}
